﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
    public class DBHelper
    {
        public static string connStr = "Data Source=.;Initial Catalog=atm;Integrated Security=True;Encrypt=False";//数据库连接字符串
        public static SqlConnection conn = null;//数据库连接对象

        //打开数据库
        public static void initConnection()
        {
            if (conn == null)
            {
                conn = new SqlConnection(connStr);
            }
            if (conn.State == ConnectionState.Broken)
            {
                conn.Close();
                conn.Open();
            }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
        }

        /// <summary>
        /// 执行增删改
        /// </summary>
        /// <param name="sql">sql命令</param>
        /// <returns>执行结果是否成功</returns>
        public static bool ExecuteSql(string sql)
        {
            initConnection();
            SqlCommand cmd = new SqlCommand(sql, conn);
            int res = cmd.ExecuteNonQuery();
            conn.Close();
            return res > 0;
        }

        /// <summary>
        /// 获取数据表信息
        /// </summary>
        /// <param name="sql">sql命令</param>
        /// <returns>数据表</returns>
        public static DataTable GetDataTable(string sql)
        {
            initConnection();
            DataTable dt = new DataTable();
            SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
            adapter.Fill(dt);
            conn.Close();
            return dt;
        }
    }
}